<?php
/**
 * Date: 2024.8
 * Author: kahn
 * 微信小程序微信授权登录
 */
use config\Config;
use config\Response;
use service\uc\OauthService;
use models\uc\OauthModel;
use models\uc\UserModel;
use service\uc\UserService;

class MicroController extends Controller
{
    /**
     * 根据小程序客户端传来的code获取unionid session_key等信息
     * 如果用户已经授权登录过, 则进行登录操作
     */
    public function loginAction(): void
    {
        $code = $this->_getParam('code','string');

        $auth = OauthService::getWxMicroClient()->code2session($code);
        if(!$auth){
            $this->_response(Response::WXMICRO_UNIONID_FAIL);
        }

        $json_arr= json_decode($auth,true);
        if(!$json_arr || ($json_arr['errcode'] ?? 0) != 0 ){
            \Log::error('login code2sesson error ', $auth);
            $this->_response(Response::WXMICRO_UNIONID_FAIL);
        }
        $unionId = $json_arr['unionid'] ?? $json_arr['openid'];

        $oauth = OauthModel::where('unionId',$unionId)->findOrEmpty();
        if($oauth->isEmpty()){  //微信用户还没进行过授权登录, 返回客户端等待客户端获得获取手机号授权
            $this->_response(Response::WXMICRO_UNBIND, ['unionId'=>$unionId]);
        }

        $user = UserModel::findOrEmpty($oauth->userId);
        $retCode = Response::SYSTEM_ERROR;
        if($user->isEmpty() || !UserService::check($user, $retCode)){
            $this->_response($retCode);
        }

        $ret = UserService::doLogin($user->id, Config::REGISTER_LOGIN_TYPE_WX, $token);
        if(!$ret){
            $this->_response(Response::SYSTEM_ERROR);
        }else{
            $this->_response(Response::SUCCESS, ['token'=>$token]);
        }
    }

    /**
     * 根据小程序客户端传过来的code,向微信获取手机号
     * 根据手机号进行登录/注册操作, 并进行userId和unionid的绑定
     */
    public function bindAction(): void
    {
        $code = $this->_getParam('code','string',true);
        $unionId = $this->_getParam('unionId','string',true);
        $mobile = '';

        $ret = (OauthService::getWxMicroClient())->getPhoneNumber($code, $mobile);
        if(!$ret){
            $this->_response(Response::WXMICRO_MOBILE_FAIL);
        }
        $ret = OauthService::login($unionId, $mobile, $userId, $token);



        if($ret != Response::SUCCESS){
            $this->_response($ret);
        }
        $this->_response($ret, ['token'=>$token, 'mobile'=>$mobile]);
    }

}

